package vinux.web.common.es;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import vinux.service.common.statics.SysConstant;
import vinux.service.common.util.CollectionUtils;
import vinux.service.core.elasticsearch.utils.ElasticsearchManager;
import vinux.service.entity.tchange.TChange;
import vinux.service.entity.userbaseinfo.UserBaseInfo;
import vinux.service.service.tchange.service.TChangeService;
import vinux.service.service.userbaseinfo.service.UserBaseInfoService;
import vinux.web.common.es.bo.UserInfoBo;


public class SyncWorker implements Runnable {
	
	private UserBaseInfoService userService;
	
	private TChangeService changeService;
	
	public SyncWorker(){
		
	}

	public  SyncWorker(UserBaseInfoService userService,TChangeService changeService){
		this.userService = userService;
		this.changeService = changeService;
	}

	@Override
	public void run() {
		while(true){
			try {
				Thread.sleep(10000);
				List<TChange> changeList = CollectionUtils.newArrayList();
				changeList = changeService.selectAllUnSync();
				for(TChange change : changeList){
					
					UserBaseInfo user = userService.selectByPrimaryKey(Long.valueOf(change.getPid()));
					if(user!=null && user.getId()!=null){
						UserInfoBo userBo = new UserInfoBo(user);
						JSONObject userJson = JSONObject.fromObject(userBo);
						JSONArray userJArray = JSONArray.fromObject(userJson);
						ElasticsearchManager.save(SysConstant.MANAGER_INDEX, SysConstant.MANAGER_TYPE_USER_BASE_INFO, "id",userJArray );
						Map<String,Object> param = CollectionUtils.newHashMap();
						param.put("id", change.getId());
						changeService.updateSyncStatus(param);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
}
